let sysBBS = `<span style='font-size:14px; line-height:30px;'>欢迎来到网络聊天室，请遵守聊天室规则，不要使用不文明用语。</span>
                      <br>
                      <span style='line-height:22px;'/>
                      `;

let intervalShowContent = window.setInterval("showContent();", 1000);
let intervalShowOnLine = window.setInterval("showOnLine();", 10000);
let intervalCheck = window.setInterval("check();", 1000);

$(function () {
    showOnLine();
    showContent();
    check();
});

/**
 * 检测用户的session是否存在
 */
function check() {
    $.ajax({
        url: "/user/check",
        contentType: "application/json;charset=UTF-8",
        success(res) {
            if (res) {
                console.log(res)
                stopAllInterval();
                // 提示用户下线
                alert("您已经被踢下线了!");
                // 回到登录页面!
                window.location = "/login";
            }
        },
        error() {
            stopAllInterval();
            // 提示用户下线
            // alert("网络错误，强制下线！");
            // 回到登录页面!
            window.location = "/login";
            // console.log(err.responseText);
        }
    })
}

// 显示在线人员列表
function showOnLine() {
    // 异步发送请求 获取在线人员列表
    // Jquery发送异步请求
    $.ajax({
        url: "/online",
        contentType: "application/json;charset=UTF-8",
        success(res) {
            $(".online-content").html(res);
            // console.log("渲染");
        }
    })
}

// 显示聊天的内容
function showContent() {
    $.ajax({
        method: "GET",
        url: "/user/getMessage",
        contentType: "application/json;charset=UTF-8",
        success(res) {
            $("#content").html(sysBBS + res);
        }
    })
}


function set(selectPerson) {	//自动添加聊天对象
    let to = $('input[name=to]')
    if (selectPerson !== $('.user-username').text()) {
        to.val(selectPerson);
    } else {
        // alert("请重新选择聊天对象！");
        // 跳转到修改个人信息页
        window.open("/userInfo");
    }
}

function send() {
    let to = $('input[name=to]')
    let content = $('input[name=content]')
    if (to.val() === "") {
        alert("请选择聊天对象！");
        return;
    }
    if (content.val() === "") {
        alert("发送信息不可以为空！");
        content.on('focus', () => {
        });
        return;
    }
    // $("#form1").serialize():让表单中所有的元素都提交.
    $.ajax({
        method: "POST",
        url: "/user/sendMessage",
        data: JSON.stringify($("#chat-form").serializeObject()),
        contentType: "application/json;charset=UTF-8"
    })
    //刷新消息
    $.ajax({
        method: "GET",
        url: "/user/getMessage",
        contentType: "application/json;charset=UTF-8",
        success(res) {
            $("#content").html(`${sysBBS}${res}</span>`);
        }
    })

    $("input[name='content']").val("").on('focus', () => {
    })
}


function exit() {
    // alert("欢迎您下次光临！");
    /*$.ajax({
        method: 'GET',
        url: "/user/logout",
        contentType: "application/json;charset=UTF-8"
    })*/
    window.location.href = "/user/logout";
}

/**
 * 停止所有的定时器
 */
function stopAllInterval() {
    console.log("停止所有计时器")
    clearInterval(intervalShowContent);
    clearInterval(intervalShowOnLine);
    clearInterval(intervalCheck);
}

/**
 * 序列化form表单，例如{id:1,name:aa,age:25}
 * 注意：form表单的每个input都必须要有name
 */
$.fn.serializeObject = function () {
    let o = {};
    let a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

/**
 * 按回车发送消息
 */
$('input[name="content"]').on('keypress', (event) => {
    if (event.key === 'Enter') {
        // console.log("发送消息");
        send();
    }
})

/**
 * 踢人按钮
 */
function kickOutUser(id) {
    $.ajax({
        url: `/user/kick?id=${id}`,
        contentType: "application/json;charset=UTF-8",
        success(res) {
            alert(res);
        },
        error(err) {
            alert(err.responseText);
        }
    });
}